package com.adamjwh.pratice.offer;

/**
 * 统计一个数字在排序数组中出现的次数。
 */
public class GetTimesOfNum {

    public int GetNumberOfK(int [] array , int k) {
        if(array == null || array.length == 0) {
            return 0;
        }

        return binarySearch(array, k+0.5) - binarySearch(array, k-0.5);
    }

    private int binarySearch(int[] arr, double k) {
        int low = 0, high = arr.length - 1;

        while (low <= high) {
            int mid = (low + high) >> 1;

            if (arr[mid] < k) {
                low = mid + 1;
            } else if (arr[mid] > k) {
                high = mid - 1;
            }
        }

        return low;
    }

}
